package com.meihua.shellapp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.meihua.shellapp.R;
import com.meihua.shellapp.base.BaseActivity;
import com.meihua.shellapp.base.MyApplication;
import com.meihua.shellapp.bean.GetScoreBean;
import com.meihua.shellapp.bean.TestContentBean;
import com.meihua.shellapp.dialog.BaseMessageDialog;
import com.meihua.shellapp.dialog.TestPassDialog;
import com.meihua.shellapp.fragment.test.TestContentFragment;
import com.meihua.shellapp.utils.FastClickUtils;
import com.meihua.shellapp.utils.LogUtils;
import com.meihua.shellapp.utils.URL;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;

/**
 * 作者：lc on 2017/9/28.
 * 邮箱：lc0607live@163.com
 */

public class TestActivity extends BaseActivity implements TestPassDialog.OnClickListener {

    @Bind(R.id.tv_title)
    TextView tv_title;//标题
    @Bind(R.id.tv_top_right)
    TextView tv_top_right;//结束测试
    @Bind(R.id.fl_test_content)
    FrameLayout fl_test_content;//测试题
    @Bind(R.id.tv_next)
    TextView tv_next;//下一题
    @Bind(R.id.tv_previous)
    TextView tv_previous;//上一题

    private int mPage = 1;//第几题
    private int mS = 0;//倒计时（s）

    private List<TestContentFragment> mFragments = new ArrayList<>();
    private List<TestContentBean.Data> data = new ArrayList<>();
    private BaseMessageDialog dialog;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                tv_title.setText("" + (mS / 60 < 10 ? "0" + (mS / 60) : mS / 60) + ":" + (mS % 60 < 10 ? "0" + (mS % 60) : mS % 60));
            } else if (msg.what == 2) {
                if(!isFinishing()) {
                    showTimeEnd();
                }
            }
        }
    };
    private TestPassDialog testPassDialog;


    @Override
    public int getLayoutId() {
        return R.layout.activity_test;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        tv_top_right.setVisibility(View.VISIBLE);
        tv_top_right.setText("结束测试");
        tv_top_right.setOnClickListener(this);
        tv_title.setVisibility(View.VISIBLE);
        tv_next.setOnClickListener(this);
        tv_previous.setOnClickListener(this);
        getTestContent();
        tv_next.setVisibility(View.VISIBLE);
    }

    private void getTestContent() {
        OkGo.<String>post(URL.getUrl().GETTESTCONT)
                .tag(this)
                .params("member_num", MyApplication.getInstance().getUserId())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        TestContentBean bean = (TestContentBean) MyApplication.getInstance().getBeanForJson(TestContentBean.class, response.body());
                        if (bean == null) {
                            return;
                        }
                        if (bean.getData() != null && bean.getData().size() > 0) {
                            data = bean.getData();
                            showContentFragment(getContentFragment());
                            startCountDown(40);
                            LogUtils.getInstance().e(data.size()+"长度");
                        }
                    }
                });
    }

    /**
     * 开始倒计时功能
     *
     * @param min 倒计时从（min）分钟开始
     */
    private void startCountDown(double min) {
        mS = (int) (min * 60);

        final Timer t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(1);
                mS--;
                if (mS <= 0) {
                    t.cancel();
                    handler.sendEmptyMessage(2);
                    return;
                }
            }
        }, 0, 1000);
    }

    /**
     * 到时间了
     */
    private void showTimeEnd() {
        dialog = new BaseMessageDialog.Builder(this)
                .setCencleShow(View.GONE)
                .setMessage("您的测试时间到了,需重新测试！")
                .isCancel(false)
                .isCancelTouch(false)
                .setClickSure(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        dialog.dismiss();
                        finish();
                    }
                })
                .show();
        //请求网络

        //显示成绩
    }

    @Override
    protected void onDestroy() {
        if(dialog!=null) dialog.cancel();
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.tv_previous://上一题
                if(FastClickUtils.isFastClick()) {
                    mPage--;
                    changeUI();
                    showContentFragment(getContentFragment());
                }
                break;
            case R.id.tv_next://下一题
                if(FastClickUtils.isFastClick()) {
                    if (!getContentFragment().isCheck()) {
                        Toast.makeText(mContext, "请选择答案", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (mPage == 20) {
                        commitTest();
                        return;
                    }
                    mPage++;
                    changeUI();
                    showContentFragment(getContentFragment());
                    LogUtils.getInstance().e(mPage+"pay");
                }
                break;
            case R.id.tv_top_right://结束测试
                dialog = new BaseMessageDialog.Builder(mContext)
                        .setClickSure(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                dialog.dismiss();
                                finish();
                            }
                        }).setMessage("确定要结束测试吗？")
                        .show();
                break;
        }
    }

    private boolean isPass = false;

    private void commitTest() {
//        ToastUtils.getInstance().showToast("完成");
        Map<String, String> temp = new HashMap<>();
        JSONObject j1 = new JSONObject();
        for (int i = 0; i < mFragments.size(); i++) {
            try {
                j1.put(mFragments.get(i).getTestId() + "", mFragments.get(i).getAnswer());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        JSONObject j = new JSONObject();
        try {
            j.put("member_num", MyApplication.getInstance().getUserId());
            j.put("time_cost", 40 * 60 - mS);
            j.put("answer", j1);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkGo.<String>post(URL.getUrl().COMMITTESTCONT)
                .upJson(j)
                .execute(new StringCallback() {
                    String score = "";
                    String tx1 = "";
                    String tx2 = "";

                    @Override
                    public void onSuccess(Response<String> response) {
                        GetScoreBean bean = MyApplication.getInstance().getBeanForJson(GetScoreBean.class, response.body());
                        if (bean == null) return;
                        if (bean.getCode() == 1) {
                            //测试通过
                            score = bean.getData().getScore() + "";
                            tx1 = "恭喜您通过了本次测试!";
                            tx2 = "请再接再厉";
                            isPass = true;
                        } else {
                            //测试不通过
                            isPass = false;
                            score = bean.getData().getScore() + "";
                            tx1 = "很遗憾您的测试未通过!";
                            tx2 = "请继续努力";
                        }
                        testPassDialog = new TestPassDialog(TestActivity.this, R.style.userinfo_sex_Dialog, score, tx1, tx2, bean.getCode() == 1);
                        testPassDialog.show();
                        testPassDialog.setOnTestClickListener(TestActivity.this);
                    }
                });
    }


    /**
     * 改变UI显示
     */
    private void changeUI() {
        tv_next.setText("下一题");
        tv_previous.setVisibility(View.VISIBLE);
        if (mPage == 20) {
            tv_next.setText("完成");
        }
        if (mPage == 1) {
            tv_previous.setVisibility(View.GONE);
        }

    }

    /**
     * 获取fragment并加入集合中
     *
     * @return
     */
    private TestContentFragment getContentFragment() {
        for (TestContentFragment temp : mFragments) {
            if (mPage == temp.page) {
                return temp;
            }
        }
        TestContentFragment fragment = new TestContentFragment();
        fragment.page = mPage;
        fragment.bean = data.get(mPage - 1);
        mFragments.add(fragment);
        return fragment;
    }

    /**
     * 显示一个fragment隐藏其他
     *
     * @param fragment
     */
    private void showContentFragment(TestContentFragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (!fragment.isAdded()) {
            transaction.add(R.id.fl_test_content, fragment);
        }
        for (int i = 0; i < mFragments.size(); i++) {
            if (mFragments.get(i) == fragment) {
                transaction.show(fragment);
            } else {
                transaction.hide(mFragments.get(i));
            }
        }
        transaction.commit();
    }

    /*完成弹框点击*/
    @Override
    public void okClick(View view) {
        testPassDialog.dismiss();
        if (!isPass) {
            startActivity(new Intent(this, TestActivity.class));
        }
        finish();
    }
}
